package com.landun.market.pojo.enums;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jiang.chuan
 * @date 2018-05-11
 */
public enum UserType implements IEnumType {
    PLATFORM(1, "平台端"),
    MOBILE(9, "移动端");

    private final static Map<Integer, UserType> BY_CODE_MAP
            = Arrays.stream(UserType.values()).collect(Collectors.toMap(UserType::code, code -> code));

    private final static Map<String, UserType> BY_NAME_MAP
            = Arrays.stream(UserType.values()).collect(Collectors.toMap(code -> code.name().toLowerCase(), code -> code));


    private final int code;
    private final String desc;

    /**
     * @param code 代码
     * @param desc 描述
     */
    UserType(final int code, final String desc) {
        this.code = code;
        this.desc = desc;
    }

    @Override
    public int code() {
        return this.code;
    }

    @Override
    public String desc() {
        return this.desc;
    }

    /**
     * @param code 代码
     * @return 转换出来的状态码
     */
    public static UserType parse(Integer code) {
        return BY_CODE_MAP.get(code);
    }

    public static UserType parse(Integer code, UserType defaultType) {
        return BY_CODE_MAP.getOrDefault(code, defaultType);
    }

    /**
     * @param name 名字
     * @return 转换出来的状态码
     */
    public static UserType parse(String name) {
        if (StringUtils.isBlank(name)) {
            return null;
        }
        return BY_NAME_MAP.get(name.trim().toLowerCase());
    }

    public static UserType parse(String name, UserType defaultType) {
        if (StringUtils.isBlank(name)) {
            return defaultType;
        }
        return BY_NAME_MAP.getOrDefault(name.trim().toLowerCase(), defaultType);
    }
}
